package com.keyancompany.zhongbaopingtai.activity;

import android.os.Bundle;
import android.support.design.widget.TextInputLayout;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;

import com.alibaba.fastjson.JSONArray;
import com.keyancompany.zhongbaopingtai.R;
import com.keyancompany.zhongbaopingtai.api.TeamAPI;
import com.keyancompany.zhongbaopingtai.api.UserAPI;
import com.keyancompany.zhongbaopingtai.listener.IAsyncHttpResponseHandler;
import com.keyancompany.zhongbaopingtai.model.BaseModel;
import com.keyancompany.zhongbaopingtai.model.Labels;
import com.keyancompany.zhongbaopingtai.model.TechnologyEntity;
import com.keyancompany.zhongbaopingtai.utils.DateUtils;
import com.keyancompany.zhongbaopingtai.utils.T;
import com.keyancompany.zhongbaopingtai.weight.DatePopupWindow;
import com.keyancompany.zhongbaopingtai.weight.MenuPopuWindow;
import com.keyancompany.zhongbaopingtai.weight.SelectFenLeiPopup;

import java.util.Calendar;
import java.util.List;

import butterknife.Bind;
import butterknife.BindString;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 创建发包
 * <p/>
 * Created by firefox on 2016/6/14.
 */
public class CreatePackageActivity extends BaseActivity {
    @BindString(R.string.create_package_text)
    String title;

    @Bind(R.id.toolbar)
    Toolbar toolbar;
    @Bind(R.id.project_title)
    EditText projectTitle;
    @Bind(R.id.project_attr)
    RadioGroup projectAttr;
    @Bind(R.id.private_project)
    RadioButton privateProject;
    @Bind(R.id.public_project)
    RadioButton publicProject;
    @Bind(R.id.project_phone)
    EditText projectPhone;
    @Bind(R.id.submit)
    TextView submit;
    @Bind(R.id.stop_time)
    TextView stopTime;
    @Bind(R.id.project_budget)
    EditText projectBudget;

    @Bind(R.id.project_desc)
    EditText projectDesc;
    @Bind(R.id.spinner)
    Spinner spinner;
    @Bind(R.id.fenshu)
    EditText fenshu;
    @Bind(R.id.fenshu_parent)
    LinearLayout fenshuParent;
    @Bind(R.id.fenshu_line)
    View fenshuLine;
    @Bind(R.id.project_type_parent)
    LinearLayout projectTypeParent;
    @Bind(R.id.zhongbiao_type_parent)
    LinearLayout zbTypeParent;
    @Bind(R.id.level_select)
    Button levelSelect;
    @Bind(R.id.one_level_tag)
    Button oneLevelTag;
    @Bind(R.id.two_level_tag)
    Button twoLevelTag;
    @Bind(R.id.project_budget_parent)
    TextInputLayout projectBudgetParent;
    @Bind(R.id.stop_time_parent)
    LinearLayout stopTimeParent;


    private int proAttr = 0;
    private String techId;
    private DatePopupWindow datePopupWindow;
    private String endTime;
    private String parentId = "363c578caa544cff8c26cc3256bc47d5";
    private String oneLevel, twoLevel, threeLevel;


    @Override
    protected int getContentViewId() {
        return R.layout.activity_create_package;
    }

    @Override
    protected int getMenuId() {
        return 0;
    }

    @Override
    protected void initToolBar() {
        initToolBar(toolbar, title);

    }

    @Override
    protected void setUpViews() {
        // 建立Adapter并且绑定数据源
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, TechnologyEntity.getTechnologyValueList());
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        //绑定 Adapter到控件
        spinner.setAdapter(adapter);
        spinner.setSelection(0);
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                techId = TechnologyEntity.getTechnologyId(TechnologyEntity.getTechnologyValueList().get(i));
                if (i == 3) {
                    fenshuParent.setVisibility(View.VISIBLE);
                    fenshuLine.setVisibility(View.VISIBLE);
                } else {
                    fenshuParent.setVisibility(View.GONE);
                    fenshuLine.setVisibility(View.GONE);
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });
        techId = TechnologyEntity.getTechnologyId(TechnologyEntity.getTechnologyValueList().get(0));
        projectAttr.check(R.id.private_project);
        projectAttr.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                if (i == R.id.private_project) {
                    proAttr = 0;
                    zbTypeParent.setVisibility(View.VISIBLE);
                    projectTypeParent.setVisibility(View.GONE);
                    projectBudgetParent.setVisibility(View.VISIBLE);
                    stopTimeParent.setVisibility(View.VISIBLE);
                } else {
                    proAttr = 1;
                    zbTypeParent.setVisibility(View.GONE);
                    projectTypeParent.setVisibility(View.VISIBLE);
                    projectBudgetParent.setVisibility(View.GONE);
                    stopTimeParent.setVisibility(View.GONE);

                }
            }
        });


    }

    @OnClick(R.id.submit)
    public void sendReqeustHttp(View v) {
        sendRequest();
    }

    @OnClick(R.id.level_select)
    public void selectLevel(View view) {
        UserAPI.fenlei(parentId, new FenLeiListener(0), getLoading(R.string.watting_hint));
    }

    @OnClick(R.id.one_level_tag)
    public void selectOneLevel(View view) {
        UserAPI.fenlei(oneLevel, new FenLeiListener(1), getLoading(R.string.watting_hint));
    }

    @OnClick(R.id.two_level_tag)
    public void selectTwoLevel(View view) {
        UserAPI.fenlei(twoLevel, new FenLeiListener(2), getLoading(R.string.watting_hint));
    }

    @OnClick(R.id.stop_time)
    public void selectStopTime(View v) {
        if (datePopupWindow == null) {
            datePopupWindow = new DatePopupWindow(mContext);
        }
        datePopupWindow.setDateListener(new DatePopupWindow.IOnSelectDateListener() {
            @Override
            public void selectDate(int year, int moth, int day) {
                Calendar calendar = Calendar.getInstance();
                calendar.set(year, moth, day);
                stopTime.setText(DateUtils.formatDate("yyyy-MM-dd ", calendar.getTimeInMillis()));
            }
        });
        datePopupWindow.showAtLocation(v, Gravity.CENTER, 0, 0);
    }

    public void sendRequest() {
        String title = projectTitle.getText().toString();
        String endTime = stopTime.getText().toString();
        String phone = projectPhone.getText().toString();
        String budgetText = projectBudget.getText().toString();
        String desc = projectDesc.getText().toString();
        if (TextUtils.isEmpty(title)) {
            T.showShort(this, "请输入标题");
            return;
        }
        if (TextUtils.isEmpty(phone)) {
            T.showShort(this, "请输入手机号");
            return;
        }
        if (TextUtils.isEmpty(endTime)) {
            T.showShort(this, "请输入截止日期");
            return;
        }
        if (TextUtils.isEmpty(budgetText)) {
            T.showShort(this, "请输入预算");
            return;
        }
        String fenshuText = fenshu.getText().toString();
        if (techId.equals("66e5493bbe7e4776aef8e50503aaf513") && TextUtils.isEmpty(fenshuText)) {
            T.showShort(this, "计件报酬份数必填");
            return;
        }
        if (TextUtils.isEmpty(desc)) {
            T.showShort(this, "请输入项目描述");
            return;
        }
//        if (proAttr == 1) {
//            if (levelSelect.getTag() == null || oneLevelTag.getTag() == null || twoLevelTag.getTag() == null) {
//                T.showShort(this, "请选择学术分类");
//                return;
//            }
//        }
        TeamAPI.addProject(null, "" + proAttr, title, phone, techId, desc, endTime, budgetText,
                fenshuText, levelSelect.getTag() == null ? "" : levelSelect.getTag().toString(),
                oneLevelTag.getTag() == null ? "" : oneLevelTag.getTag().toString(),
                twoLevelTag.getTag() == null ? "" : twoLevelTag.getTag().toString()
                , this, getLoading(R.string.watting_hint));
    }


    @Override
    public void success(int type, String json) {
        BaseModel base = validateJson(json);
        if (base == null) return;
        if (base.isSuccess()) {
            finish();
        } else
            T.showShort(this, base.msg);

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    public class FenLeiListener implements IAsyncHttpResponseHandler {
        private int tag; // 0 一级菜单  1二级菜单 2 三级菜单

        public FenLeiListener(int tag) {
            this.tag = tag;
        }

        @Override
        public void start(int type) {

        }

        public void setData(Button targetButton, String... param) {
            targetButton.setVisibility(View.VISIBLE);
            targetButton.setTag(param[0]);
            targetButton.setText(param[1]);
        }

        @Override
        public void success(int type, String json) {
            BaseModel baseModel = validateJson(json);
            if (baseModel.isSuccess()) {
                final List<Labels> labelses = JSONArray.parseArray(baseModel.data, Labels.class);
                if (labelses.isEmpty()) {
                    return;
                }
                final SelectFenLeiPopup popup = new SelectFenLeiPopup(mContext);
                popup.setLabels(labelses);
                popup.setCliclSureListener(new MenuPopuWindow.ClickSureListener() {
                    @Override
                    public void clickSureLinstener(String... param) {
                        popup.dismiss();
                        if (tag == 0) {
                            setData(levelSelect, param);
                            oneLevel = param[0];
                            UserAPI.fenlei(param[0], new FenLeiListener(1), getLoading(R.string.watting_hint));
                        } else if (tag == 1) {
                            setData(oneLevelTag, param);
                            twoLevel = param[0];

                            UserAPI.fenlei(param[0], new FenLeiListener(2), getLoading(R.string.watting_hint));
                        } else if (tag == 2) {
                            setData(twoLevelTag, param);
                        }
                    }
                });
                popup.showAtLocation(levelSelect, Gravity.CENTER, 0, 0);
            }
        }

        @Override
        public void failed(String error) {

        }

        @Override
        public void finish(int type) {

        }
    }
}
